package com.wlz.controller;

import com.alibaba.excel.ExcelWriter;
import com.wlz.service.OrderService;
import com.wlz.service.dto.OrderDTO;
import com.wlz.utils.EasyExcelHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

/**
 * @author throwable
 * @version v1.0
 * @description
 * @since 2020/7/11 16:45
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping(path = "/order1")
public class Order1Controller {

    private final OrderService orderService;

    /**
     *  导出百万条数据 多 sheet
     * @param paymentDateTimeStart
     * @param paymentDateTimeEnd
     * @param response
     * @throws Exception
     */
    @GetMapping(path = "/export")
    public void export(@RequestParam(name = "paymentDateTimeStart") String paymentDateTimeStart,
                       @RequestParam(name = "paymentDateTimeEnd") String paymentDateTimeEnd,
                       HttpServletResponse response) throws Exception {
        long start = System.currentTimeMillis();

        int count = 0;
        EasyExcelHandler handler = null;
        ExcelWriter excelWriter = null;

        try {
            handler = new EasyExcelHandler();
            String fileName = URLEncoder.encode(String.format("%s-(%s).xlsx", "订单支付数据", UUID.randomUUID().toString()),
                    StandardCharsets.UTF_8.toString());
            excelWriter = handler.create(fileName, OrderDTO.class,response,100);

            long lastBatchMaxId = 0L;
            int limit = 500;
            for (; ; ) {
                List<OrderDTO> list = orderService.queryByScrollingPagination(paymentDateTimeStart, paymentDateTimeEnd, lastBatchMaxId, limit);
                if (list.isEmpty()) {
                    handler.finish(excelWriter);
                    break;
                } else {
                    lastBatchMaxId = list.stream().map(OrderDTO::getId).max(Long::compareTo).orElse(Long.MAX_VALUE);
                    count += list.size();
                    handler.write(excelWriter,list,count);
                }
            }
        } catch (Exception e) {
            log.error("export 数据导出异常:",e);
        }
        log.info("count:"+ count);
        log.info("导出数据耗时:{} ms,start:{},end:{}", System.currentTimeMillis() - start, paymentDateTimeStart, paymentDateTimeEnd);
    }
}
